package com.xjc.agent;

import com.xjc.agent.core.intercept.EnhanceListener;
import com.xjc.agent.core.intercept.MonitorMethod;
import com.xjc.agent.core.util.AgentUtil;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;

import java.io.File;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author: 谢君臣
 * @Date: 2023/1/1-16:52
 * @version: 1.0
 * @function:
 */

public class PreMain {

    public static void premain(String args, Instrumentation inst) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        try {
            System.out.println("==========start preMain========");
            String agentPath = AgentUtil.findAgentDirPath();
            String libPath = File.separator + "lib";
            String confPath = File.separator + "conf";
            String pluginPath = File.separator + "plugin";
            ClassLoader rootClassLoader = ClassLoader.getSystemClassLoader().getParent();
            AgentLoader agentClassLoader = new AgentLoader(agentPath, libPath, confPath, rootClassLoader);
            Class<?> agentBootstrap = agentClassLoader.loadClass("com.xjc.agent.core.AgentBootstrap");
            Method bootstrapMethod = agentBootstrap.getMethod("main", String.class, Instrumentation.class);
            bootstrapMethod.invoke(agentBootstrap.newInstance(),args,inst);
        } catch (NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
